package com.kingwang.demo.springsecuritytokendemo.security;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登出处理器
 */
public class TokenLogoutHandler implements LogoutHandler {
    private TokenSessionManager sessionManager;

    protected TokenSessionManager getSessionManager() {
        return this.sessionManager;
    }

    public TokenLogoutHandler(TokenSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();
        }

        final String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isNotBlank(authorizationHeader)) {
            String[] tokenParts = authorizationHeader.split(" ");

            if (tokenParts.length == 2) {
                String tokenSessionId = this.sessionManager.generateSessionId(
                        tokenParts[0],
                        tokenParts[1]);

                getSessionManager().removeSession(tokenSessionId);
            } else {
                throw unsupportedOperationException("Token格式非法！");
            }
        }
//        else {
//            throw unsupportedOperationException("未找到Token！");
//        }
    }

    private static UnsupportedOperationException unsupportedOperationException(String message) {
        return new UnsupportedOperationException(message);
    }
}
